<script setup lang="ts">
import { ref } from 'vue'
import { type FormInstance, Message } from '@arco-design/web-vue'
import dayjs from 'dayjs'
import ArrangeCalendar from '@/views/system/business/rules/ArrangeTemplate/components/ArrangeCalendar.vue'
import { useForm } from '@/hooks'
import { ArrangeTemplateApi } from '@/apis/education'

const emit = defineEmits(['change'])

const visible = ref(false)
const loading = ref(false)
const readonly = ref(true)

const dataId = ref<string>('')

const isCopyMode = ref(false)
const isCreateMode = computed(() => dataId.value === '')
const title = computed(() => (isCreateMode.value ? '创建模板' : '编辑模板'))

const formRef = ref<FormInstance>()
const { form, resetForm } = useForm({
  name: '',
  fullName: '',
  classYear: new Date().getFullYear().toString(),
  term: '',
  grade: '',
  arrangeLessonList: [],
})

const rules: FormInstance['rules'] = {
  name: [{ required: true, message: '请输入名称' }],
  fullName: [{ required: true, message: '请输入完整名称' }],
  classYear: [{ required: true, message: '请选择上课年份' }],
  term: [{ required: true, message: '请选择学期' }],
  grade: [{ required: true, message: '请选择年级' }],
}

// 上课日期列表
const lessonDateList = ref([])
watch(lessonDateList, (val) => {
  form.arrangeLessonList = val.map((item: any) => ({
    lessonIndex: item.lessonIndex,
    lessonDate: dayjs(item.lessonDate).format('YYYY-MM-DD'),
  }))
}, { deep: true })

// 保存
const onSave = async () => {
  const isInvalid = await formRef.value?.validate()
  if (isInvalid) {
    return false
  }
  if (!form.arrangeLessonList.length) {
    Message.warning('请选择课次')
    return false
  }

  if (isCreateMode.value || isCopyMode.value) {
    await ArrangeTemplateApi.createArrangeTemplate(form)
    Message.success('添加成功')
  } else {
    await ArrangeTemplateApi.updateArrangeTemplate(form, dataId.value)
    Message.success('编辑成功')
  }
  emit('change')
  visible.value = false
  return true
}

const reset = () => {
  resetForm()
  lessonDateList.value = []
  formRef.value?.clearValidate()
}

// 查询详情
const getDataDetail = async () => {
  loading.value = true
  const dataDetail = await ArrangeTemplateApi.getArrangeTemplateDetail(dataId.value)
  for (const key in form) {
    form[key] = dataDetail?.[key]
  }
  form.classYear = `${form.classYear}`
  lessonDateList.value = (dataDetail.arrangeLessonList || []).map(item => ({
    lessonIndex: item.lessonIndex,
    lessonDate: new Date(item.lessonDate),
  }))
  loading.value = false
}

// 打开详情
const open = async (id: string) => {
  dataId.value = id
  loading.value = true
  visible.value = true
  readonly.value = true
  isCopyMode.value = false
  getDataDetail()
}

// 打开新增
const create = async () => {
  dataId.value = ''
  loading.value = false
  visible.value = true
  readonly.value = false
}

// 打开新增
const copy = async (id: string) => {
  open(id)
  readonly.value = false
  isCopyMode.value = true
}

defineExpose({ open, create, copy })
</script>

<template>
  <ProFormPanel
    v-model:visible="visible"
    mode="modal"
    :max-width="960"
    :title="title"
    :loading="loading"
    :footer="true"
    @confirm="onSave"
    @close="reset"
  >
    <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
      <a-row :gutter="40">
        <a-col :span="12">
          <a-form-item label="全称" field="fullName" tooltip="用于内部展示">
            <a-input v-model.trim="form.fullName" placeholder="请输入全称（用于内部展示）" />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="简称" field="name" tooltip="用于家长展示">
            <a-input v-model.trim="form.name" placeholder="请输入名称（用于家长展示）" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="40">
        <a-col :span="6">
          <a-form-item label="上课年份" field="classYear">
            <a-year-picker v-model="form.classYear" placeholder="选择上课年份" />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="年级" field="grade">
            <DictSelect v-model="form.grade" code="Grade" placeholder="选择年级" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="学期" field="term">
            <DictSelect v-model="form.term" type="button" code="TermEnum" />
          </a-form-item>
        </a-col>
      </a-row>
      <div class="h-450px">
        <ArrangeCalendar v-model="lessonDateList" />
      </div>
    </a-form>
  </ProFormPanel>
</template>

<style lang="less" scoped>
.content {
  display: grid;
  grid-template-rows: repeat(2, 1fr);
  grid-template-columns: repeat(2, 1fr);
  column-gap: 30px;

  .grid-item-large {
    grid-column: span 2;
  }
}

// .wrap {
//   height: 450px;
// }
// :deep(.arco-radio-checked) {
//   background: rgb(var(--primary-6));
//   color: #fff;
// }
</style>
